"""
Case Type   : 资源池化
Case Name   : 扩容成功后，主备倒换测试
Create At   : 2024.10
Owner       : chen
Description :
    1.扩容单个备机
    gs_expansion -U {user} -G {user} -X {xml} -h {ip1}
    2.检查扩容情况
    cm_ctl -query -Cv
    查看各节点pg_hba.conf配置文件有无新节点信息
    3.主备倒换，将扩容节点升主，旧主机降备，开启TPCC业务
    4.缩容新加入节点，恢复环境
Expect      :
    1.成功
    2.检查成功
    3.主备倒换成功；TPCC业务无异常
    4.缩容成功；恢复环境成功
"""

import os
import unittest
import time
from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Common import Common
from testcase.utils.Constant import Constant
from yat.test import Node
from yat.test import macro

class SharedStorage(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_node = Node('PrimaryDbUser')
        self.pri_root_node = Node('PrimaryRoot')
        self.sta2_node = Node('Standby2DbUser')
        self.root_usernode = Node('Standby2DbUser')
        self.commsh = CommonSH('PrimaryDbUser')
        self.sta2_commsh = Common('Standby2DbUser')
        self.constant = Constant()
        self.db_host = self.sta2_node.db_host
        self.s_user = self.pri_node.ssh_user
        self.pri_pg = 'pri_props.pg'
        self.pri_tpcc_log = 'pri_tpcc_result.log'

    def test_shared_storage(self):
        text = "-----step1: 扩容单个备机 expect: 成功-----"
        self.log.info(text)
        xml_path = macro.DB_XML_PATH
        cmd = f'''gs_expansion -U {self.s_user} \
            -G {self.s_user} -X {xml_path} -h {self.db_host}'''
        execute_cmd = f'''source {macro.DB_ENV_PATH};
            expect <<EOF
            set timeout 300
            spawn {cmd}
            expect "*assword*:"
            send "{self.pri_root_node.ssh_password}\\n"
            expect "*assword*:"
            send "{self.pri_root_node.ssh_password}\\n"
            expect "*lease repeat for database*:"
            send "{macro.GAUSSDB_INIT_USER_PASSWD}\\n"
            expect eof\n''' + '''EOF'''
        self.log.info(execute_cmd)
        res = self.pri_root_node.sh(execute_cmd).result()
        self.log.info(res)
        self.assertIn(f'{self.db_host}:\tSuccess', res)

        text = f'-----step2: 检查扩容情况 expect: 检查成功-----'
        self.log.info(text)
        res = self.commsh.exec_cm_ctl('query', '-Cv')
        self.log.info(res)
        node_arr = res.splitlines()[-1].split('|')
        for node_mes in node_arr:
            self.assertIn('Normal', node_mes)
        cmd = f'''cat {macro.DB_INSTANCE_PATH}/postgresql.conf | grep {self.db_host}'''
        self.log.info(cmd)
        res = self.pri_node.sh(cmd).result()
        self.log.info(res)
        self.assertIn(f'{self.db_host}', res)
        cmd = f'''cat {macro.DB_INSTANCE_PATH}/postgresql.conf | grep {self.pri_node.db_host}'''
        self.log.info(cmd)
        res = self.sta2_node.sh(cmd).result()
        self.log.info(res)
        self.assertIn(f'{self.pri_node.db_host}', res)
        cmd = f'''cat {macro.DB_INSTANCE_PATH}/pg_hba.conf | grep {self.db_host}'''
        self.log.info(cmd)
        res = self.pri_node.sh(cmd).result()
        self.log.info(res)
        self.assertIn(f'{self.db_host}', res)
        cmd = f'''cat {macro.DB_INSTANCE_PATH}/pg_hba.conf | grep {self.pri_node.db_host}'''
        self.log.info(cmd)
        res = self.sta2_node.sh(cmd).result()
        self.log.info(res)
        self.assertIn(f'{self.pri_node.db_host}', res)

        text = "-----step3: 主备倒换，将扩容节点升主，旧主机降备，开启TPCC业务" \
            " expect: 成功-----"
        self.log.info(text)
        res = self.commsh.exec_cm_ctl('switchover', '-n 3 -D $PGDATA')
        self.log.info(res)
        self.assertIn(self.constant.cm_switchover_success_msg, res)
        pri_tpcc = self.sta2_commsh.startTPCC(self.root_usernode,
                                      self.pri_pg,
                                      self.pri_tpcc_log)
        self.log.info(pri_tpcc)
        time.sleep(30)
        pri_res = self.root_usernode.sh(f'cat {macro.TPCC_PATH}/{self.pri_tpcc_log}').result()
        self.log.info(pri_res)
        self.assertIn('Current tmpTOTAL', pri_res, 'tpcc业务执行失败')

    def tearDown(self):
        text = "-----step4: 恢复环境 expect: 成功-----"
        self.log.info(text)
        self.log.info('-----停止tpcc业务-----')
        tpcc_pid = self.sta2_commsh.get_pid(self.root_usernode,
                                    f'"{self.pri_pg}"')
        self.log.info(tpcc_pid)
        stop_tpcc = self.root_usernode.sh(f'kill -9 {tpcc_pid}').result()
        self.log.info(stop_tpcc)
        res = self.commsh.exec_cm_ctl('switchover', '-a')
        self.log.info(res)
        self.assertIn(self.constant.cm_switchover_success_msg, res)
        cmd = f'''source {macro.DB_ENV_PATH};
            expect <<EOF
            set timeout 600
            spawn gs_dropnode -U {self.s_user} -G {self.s_user} \
            -h {self.db_host}
            expect "*drop the target node (yes/no)?*"
            send "yes\\n"
            expect eof\n''' + '''EOF'''
        self.log.info(cmd)
        res = self.pri_node.sh(cmd).result()
        self.log.info(res)
        self.assertIn('Success to drop the target nodes', res)
        res = self.sta2_node.sh(f'source {macro.DB_ENV_PATH}; ' \
            'gs_uninstall --delete-data').result()
        self.log.info(res)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')